package com.example.algorithm.tree;

import com.example.algorithm.datastructure.TreeNode;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yuzhenxin
 * @date 2023-02-10 23:18
 * @description Leetcode-105：从前序与中序遍历序列构造二叉树
 */
public class BuildTree {
    Map<Integer, Integer> pIndexMap = new HashMap<>();

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        for (int i = 0; i < inorder.length; i++) {
            // 记录中序遍历每个值的下标位置，空间换时间
            pIndexMap.put(inorder[i], i);
        }
        return buildTree(preorder, 0, preorder.length - 1, 0, inorder.length - 1);
    }

    private TreeNode buildTree(int[] preorder, int preLeft, int preRight, int inLeft, int inRight) {
        if (preLeft > preRight || inLeft > inRight) {
            return null;
        }
        // 先序遍历的第一个元素为根节点
        int rootVal = preorder[preLeft];
        TreeNode root = new TreeNode(rootVal);
        Integer pIndex = pIndexMap.get(rootVal);
        // 前序：根-左-右
        //preLeft, [preLeft + 1, x], [x + 1 ,preRight]
        // 中序：左-中-右
        // [inLeft, pIndex - 1], pIndex , [pIndex + 1, inRight]
        // x - preLeft - 1 = pIndex - 1 - inLeft => x = pIndex - inLeft + preLeft
        root.setLeft(buildTree(preorder, preLeft + 1, pIndex - inLeft + preLeft, inLeft, pIndex - 1));
        root.setRight(buildTree(preorder, pIndex - inLeft + preLeft + 1, preRight, pIndex + 1, inRight));
        return root;
    }
}